<?

class AccountController extends CFD_Controller_Action {

    const passwordSalt = "l3tm31n";

    public function init() {
        parent::init();
    }

    public function profileAction() {
        $this->isLogged(true);
        $this->view->title = "Edit profile";

        $this->view->showEmail = false;
        $this->view->skipPassword = $this->view->skipEmail = true;

        if ($_POST) {
            unset($_POST['email']);
            unset($_POST['password']);
            $userAr = $_POST;
            $userAr['id'] = $this->user->id;

            $usersTable = new Application_Model_Users();
            $userRow = $usersTable->fetchByEmail($this->user->email);

            foreach ($userAr as $k => $v)
                if ($userRow->offsetExists($k))
                    $userRow->{$k} = $v;

            $userRow->save();

            $userSession = new Zend_Session_Namespace('user');
            $this->user = $this->view->user = $userSession->user = (object) $userRow->toArray();
        }

        $this->view->formData = (array) $this->user;
    }

    public function newPasswordAction() {
        $this->view->title = "Forgot password";

        $usersTable = new Application_Model_Users();

        $select = $usersTable->select()->where('remind_hash = ?', (string) $_GET['key']);
        $usersRow = $usersTable->fetchRow($select);

        if (!$usersRow || !$usersRow->remind_hash)
            $this->getResponse()->setRedirect('/');

        if (($usersRow->remind_stamp + 24 * 60 * 60) < time()) {
            $this->view->hideForm = true;
            Alert_View::addMessage(Alert_View::NOTICE, "", "You can't change your password anymore. Please use <a href='/account/forgot-password'>Forgot Password</a>.");
            return;
        }
        if ($_POST['password'] != $_POST['password2']) {
            Alert_View::addMessage(Alert_View::NOTICE, "", "Passwords don't match. Please try again.");
        }

        if ($_POST['password'] && $_POST['password'] == $_POST['password2']) {
            $this->view->hideForm = true;
            Alert_View::addMessage(Alert_View::NOTICE, "", "Your password was successfully changed.");
            $usersRow->remind_hash = "";
            $usersRow->remind_stamp = 0;
            $usersRow->password = md5(self::passwordSalt . $_POST['password']);
            $usersRow->save();
        }
    }

    public function forgotPasswordAction() {
        $this->view->title = "Forgot password";

        $usersTable = new Application_Model_Users();

        if ($_GET['key']) {
            if (($usersRow->remind_stamp + 24 * 60 * 60) > time()) {
                Alert_View::addMessage(Alert_View::NOTICE, "", "You recently requested password change, please follow the link in your email to reset the password.");
                return;
            }
        }

        if ($_POST['username']) {
            $usersRow = $usersTable->fetchByEmail($_POST['username']);

            if ($usersRow) {
                $this->view->hideForm = true;
                if (($usersRow->remind_stamp + 24 * 60 * 60) > time()) {
                    Alert_View::addMessage(Alert_View::NOTICE, "", "You recently requested password change, please follow the link in your email to reset the password.");
                    return;
                }

                $usersRow->remind_hash = md5("i love rock and roll" . time());
                $usersRow->remind_stamp = time();
                $usersRow->save();

                $this->view->link = "https://" . DOMAIN_NAME . "/account/new-password?key=" . $usersRow->remind_hash;

                $emailMsg = $this->view->render("account/email-remind-msg.phtml");
                $mail = new Zend_Mail();
                $mail->setBodyText($emailMsg);
                $mail->setFrom(REFER_EMAIL_ADDRESS);
                $mail->addTo($usersRow->email);
                $mail->setSubject("Password reminder - " . DOMAIN_NAME);
                $mail->send();

                Alert_View::addMessage(Alert_View::NOTICE, "", "Please follow the link in your email to reset the password.");
            }
        }
    }

    public function referAction() {
        $this->isLogged(true);

        $this->view->title = "Refer to a friend";

        $friendRefersTable = new Application_Model_FriendRefers();

        if ($_POST['email']) {
            $message = $this->view->partial("account/refer-msg.phtml", $_POST);
            $title = "I've been sourcing great trade stock from CarsForDealers";

            $friendRefersRow = $friendRefersTable->createRow();
            $friendRefersRow->users_id = $this->user->id;
            $friendRefersRow->email = $_POST['email'];
            $friendRefersRow->title = $title;
            $friendRefersRow->message = $message;

            try {
                $friendRefersRow->save();
            } catch (Exception $e) {
                $this->view->accountCreated = true;
                Alert_View::addMessage(Alert_View::NOTICE, "", $e->getMessage());
                return;
            }

            $mail = new Zend_Mail();
            $mail->setBodyText($friendRefersRow->message);
            $mail->setFrom(REFER_EMAIL_ADDRESS);
            $mail->addTo($_POST['email']);
            $mail->setSubject($title);
            $mail->send();

            Alert_View::addMessage(Alert_View::NOTICE, "", "Thank you, your message was delivered.");
        }
    }

    public function notificationsAction() {
        $this->isLogged(true);

        $usersTable = new Application_Model_Users();
        $userRow = $usersTable->fetchByEmail($this->user->email);

        if ($_POST) {
            $userRow->notifications = serialize($_POST);
            $userRow->save();

            $userSession = new Zend_Session_Namespace('user');
            $this->user = $this->view->user = $userSession->user = (object) $userRow->toArray();
        }
        $this->view->notifications = unserialize($this->user->notifications);
    }

    public function st2Action() {
        $this->view->title = "Register";
        $usersTable = new Application_Model_Users();

        if (!$_POST['email'])
            $this->getResponse()->setRedirect('/account/st1');

        $email = $_POST['email'];
        $password = $_POST['password'];
        $password2 = $_POST['password2'];

        $this->view->formData = $_POST;

        if ($email) {
            $user = $usersTable->fetchByEmail($email);
            if ($user) {
                Alert_View::addMessage(Alert_View::WARNING, "", "The email you provided is already taken, please enter different email.");
                $this->view->showEmail = true;
                return;
            }
        }

        if ($password2 != $password) {
            Alert_View::addMessage(Alert_View::WARNING, "", "Passwords don't match.");
            $this->view->showEmail = true;
            return;
        }

        $userAr['email'] = $email;
        $userAr['password'] = md5(self::passwordSalt . $password);

        $user = $usersTable->createRow($userAr);
        $user->save();

        $this->view->accountCreated = true;
        $this->view->skipForm = true;
        Alert_View::addMessage(Alert_View::NOTICE, "", "Account succesfully created.");

        $emailMsg = $this->view->render("account/welcome-msg.phtml");
        $mail = new Zend_Mail();
        $mail->setBodyText($emailMsg);
        $mail->setFrom(REGISTER_EMAIL_ADDRESS);
        $mail->addTo($email);
        $mail->setSubject(DOMAIN_NAME . " Registration Email");
        $mail->send();
    }

    public function st1Action() {
        
    }

    public function logoutAction() {
        $userSession = new Zend_Session_Namespace('user');
        $userSession->user = null;

        $this->render('login');
    }

    public function loginAction() {
        $userSession = new Zend_Session_Namespace('user');
        if ($_POST['username']) {
            $usersTable = new Application_Model_Users();
            $user = $usersTable->fetchByEmail($_POST['username']);

            if (!$user) {
                Alert_View::addMessage(Alert_View::NOTICE, "", "User doesn't exist");
                return;
            }

            if ($user->password != md5(self::passwordSalt . $_POST['password'])) {
                Alert_View::addMessage(Alert_View::NOTICE, "", "Passwords don't match");
                return;
            }

            $userSession->user = (object) $user->toArray();
            $this->_helper->redirector->gotoUrl("/");
        }

        //if ($_POST['username'] == "admin" && md5($_POST['password']) == "c43c12b04103525df93603e5c7fce1a9")
        //{
        //  $userSession->user = (object)array('username' => $_POST['username'], 'password' => '***');
        //
	//  $this->_helper->redirector->gotoUrl("/");
        //}

        //This is the get parameter condition that is added to show when reseller account is created
        if ($_GET) {
            if (array_key_exists('reseller', $_GET)) {
                Alert_View::addMessage(Alert_View::NOTICE, "", "Partner Account succesfully created.");
            }
        }
    }

    public function activateAction() {
        $this->view->title = "Account activation";
    }

}
